package cn.pxxy.controller;

import cn.pxxy.domain.User;
import cn.pxxy.exception.LoginFailureException;
import cn.pxxy.service.UserService;
import cn.pxxy.util.CpachaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Controller("userController")
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    private static final CpachaUtil cap = new CpachaUtil();

    // 初次进入页面  用mvc
    @RequestMapping("/init")
    public String loginHtml(HttpServletRequest request, HttpSession session) {
        String code = cap.generatorVCode();
        session.setAttribute("code", code);
        request.setAttribute("codeImage", cap.generatorVCodeImage(code, true));
        return "/login";
    }

    // 刷新验证码  用 ajax ,js 获取 图片二进制数据
    @RequestMapping("/flush-image")
    public ResponseEntity<byte[]> flushImage(HttpSession session) throws IOException {
        String code = cap.generatorVCode();
        session.setAttribute("code", code);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(cap.generatorRotateVCodeImage(code,true),"jpeg",out);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        return new ResponseEntity<>(out.toByteArray(), headers, HttpStatus.OK);
    }

    @RequestMapping("/login")
    public String login(User user, String code, HttpSession session) {
        System.out.println("login..."+user);
        if(!code.equalsIgnoreCase((String) session.getAttribute("code"))){
            throw new LoginFailureException("验证码错误","尝试刷新验证码图片!");
        }
        user = userService.login(user);
        if(user==null){
            throw new LoginFailureException("账号或密码错误","请重新登录");
        }
        System.out.println(user);
        session.setAttribute("user",user);

        return "redirect:/index.html";
    }

}
